package tsb.com.html5.mail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Component
public class MailManager implements IMailManager {

	@Autowired
	private JavaMailSender mailSender;
    @Autowired
    private VelocityEngine velocityEngine;
	
    public void SmsAlert() throws Exception {
		
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message);
		
        try{
        	helper.setSubject("New request from NoiThatQuangBong");
//        	helper.setTo("marcusbui@mobifone.com.vn;minh2287@mobifone.com.vn;");
        	InternetAddress[] toAddresses = {new InternetAddress("marcusbui@mobifone.com.vn")
        									,new InternetAddress("minh2287@mobifone.com.vn")};
        	helper.setTo(toAddresses);
    		helper.setText("Sms alert!!!");
    		
            this.mailSender.send(message);
        }
        catch(MailException e) {
            e.printStackTrace();
            throw e;
        }
        catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}
    
	public void SendMail(String content) throws MessagingException, Exception {
		
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message);
		
        try{
        	helper.setSubject("[http://noithatquangbong.com] Customer Request");
        	helper.setTo("marcusbui85@yahoo.com.sg");
    		
    		Map model = new HashMap();
            model.put("content", content);
            String text = VelocityEngineUtils.mergeTemplateIntoString(
               velocityEngine, "newRequestMail.vm", model);
            helper.setText(text, true);
    		
    		// let's attach the infamous windows Sample file (this time copied to c:/)
    		/*FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
    		helper.addAttachment("CoolImage.jpg", file);
    		helper.addInline("identifier1234", res);
    		*/
    		
            this.mailSender.send(message);
        }
        catch(MailException e) {
            e.printStackTrace();
            throw e;
        }
        catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

}
